
#include <stdio.h>
#include <string>

// // ======Lock
class CLock
{
public:
    CLock()
    {
        pthread_mutex_init(&m_Mutex,NULL);
    }
    ~CLock()
    {
        pthread_mutex_destroy(&m_Mutex);
    }

    void lock()
    {
        pthread_mutex_lock(&m_Mutex);
    }

    void unlock()
    {
        pthread_mutex_unlock(&m_Mutex);
    }

private:
    pthread_mutex_t m_Mutex;		

};

// One Class only have one Object, also can use "static" to implement.
template<class T>
class CSingleton
{
public:
    static T* GetInstance()
    {
        // double check，make sure only one object will be create, even in multi thread situation
        if(m_Instance == NULL)
        {
            m_Mutex.lock();
            if(m_Instance == NULL)
            {
                // printf("GetInstance() new create\n");
                m_Instance = new T();
            }
            m_Mutex.unlock();
        }
            

        return m_Instance;
    }

    void ReleaseInstance()
    {
        if(m_Instance != NULL)
        {
            delete m_Instance;
            m_Instance = NULL;
        }
            
    }

private:
    // 隐藏起构造函数，对象构造必须通过 GetInstance 接口来构建
    CSingleton();
    static T *m_Instance;
    static CLock m_Mutex;
};

template<class T>
T* CSingleton<T>::m_Instance = NULL;

template<class T>
CLock CSingleton<T>::m_Mutex;

